import React, { Component, Fragment } from "react";
import moment from "moment";
import { DatePicker } from "antd";
import Icon from "@cbd/icon";
import { getTimeDistance, getMonth } from "../../utils/utils";

import styles from "./index.less";

const { RangePicker, MonthPicker } = DatePicker;

export default class DateItem extends Component {
  state = {
    value: getTimeDistance("date", 15),
    mode: ["date", "date"],
    selectedDate: [],
    open: false,
    close: false
  };

  handleDisabledDate = current => {
    const { mode, selectedDate = [] } = this.state;
    if (mode[0] === "date") {
      return selectedDate[0]
        ? current > moment(selectedDate[0]).add(14, "days") ||
            current < moment(selectedDate[0])
        : false;
    }
    return false;
  };

  handleCalendarChange = date => {
    this.setState({
      selectedDate: date,
      mode: ["date", "date"]
    });
  };

  onSaveDate = () => {
    const { onChange = () => {} } = this.props;
    const { value, mode } = this.state;
    const date = [];
    date[0] = value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : "";
    date[1] = value[0] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : "";

    onChange({ date, mode: mode[0] });
  };

  handleOpenChange = () => {
    this.setState(
      {
        selectedDate: []
      },
      () => {
        this.handleDisabledDate();
      }
    );
  };

  selectDate = (type, num = 1) => {
    this.setState(
      {
        value: getTimeDistance(type, num),
        mode: [type, type]
      },
      () => {
        this.onSaveDate();
      }
    );
  };

  handlePanelChange = (_, mode) => {
    this.setState(
      {
        value: getTimeDistance("month", 11),
        mode: [
          mode[0] === "date" ? "month" : mode[0],
          mode[1] === "date" ? "month" : mode[1]
        ],
        open: true
      },
      () => {
        this.handleDisabledDate();
      }
    );
  };

  handleChange = value => {
    this.setState({ value }, () => {
      this.onSaveDate();
    });
  };

  handleMonthChange = date => {
    const { value = [], selectedDate = [] } = this.state;
    if (selectedDate[0]) {
      value[1] = getMonth("end", date);
      if (value[0] > date) {
        const temp = value[0];
        value[0] = date;
        value[1] = temp;
      }
      this.setState({
        value
      });
      this.handleCloseMonthPanel();
      return;
    }
    value[0] = getMonth("start", date);
    selectedDate[0] = getMonth("start", date);
    this.setState(
      {
        value,
        selectedDate
      },
      () => {
        this.handleDisabledMonth();
      }
    );
  };

  handleDisabledMonth = current => {
    const { selectedDate = [] } = this.state;
    return selectedDate[0]
      ? current > moment(selectedDate[0]).add(12, "months") ||
          current < moment(selectedDate[0])
      : false;
  };

  handleCloseMonthPanel = () => {
    const { value = [] } = this.state;
    this.setState(
      {
        open: false,
        selectedDate: [],
        value
      },
      () => {
        this.onSaveDate();
      }
    );
  };

  handleClose = e => {
    e.preventDefault();
    e.stopPropagation();
    this.setState(
      {
        value: [],
        close: true
      },
      () => {
        this.onSaveDate();
      }
    );
  };

  render() {
    const { mode, value, open, close } = this.state;

    return (
      <div className={styles.root}>
        <div className={styles.extra}>
          <a
            className={mode[0] === "date" ? styles.currentDate : ""}
            onClick={() => this.selectDate("date", 15)}
          >
            近15天
          </a>
          <a
            className={mode[0] === "month" ? styles.currentDate : ""}
            onClick={() => this.selectDate("month", 12)}
          >
            近12月
          </a>
        </div>
        {mode[0] === "date" ? (
          <RangePicker
            value={value}
            onChange={this.handleChange}
            disabledDate={this.handleDisabledDate}
            onCalendarChange={this.handleCalendarChange}
            onOpenChange={this.handleOpenChange}
            onPanelChange={this.handlePanelChange}
            style={{ width: 256 }}
          />
        ) : (
          <div className={styles.monthRangeWrap} id="parent">
            {open && (
              <div
                className={styles.monthMask}
                onClick={this.handleCloseMonthPanel}
              />
            )}

            {!open ? (
              <div
                onClick={() =>
                  this.setState({
                    open: true,
                    selectedDate: []
                  })
                }
                onMouseMove={() =>
                  this.setState({
                    close: true
                  })
                }
                onMouseLeave={() => {
                  this.setState({
                    close: false
                  });
                }}
                className="ant-calendar-picker"
                style={{ width: "256px" }}
              >
                <span className="ant-calendar-picker-input ant-input">
                  <span
                    className="ant-calendar-range-picker-input"
                    style={{ display: "inline-block", textAlign: "left" }}
                    role={
                      value[0]
                        ? moment(value[0]).format("YYYY-MM-DD")
                        : "开始日期"
                    }
                  >
                    {value[0]
                      ? moment(value[0]).format("YYYY-MM-DD")
                      : "开始日期"}
                  </span>
                  <span>~</span>
                  <span
                    className="ant-calendar-range-picker-input"
                    style={{ display: "inline-block" }}
                    role={
                      value[0]
                        ? moment(value[1]).format("YYYY-MM-DD")
                        : "结束日期"
                    }
                  >
                    {value[0]
                      ? moment(value[1]).format("YYYY-MM-DD")
                      : "结束日期"}
                  </span>
                  {!close ? (
                    <Icon
                      type="calendar"
                      className="anticon anticon-calendar ant-calendar-picker-icon"
                      style={{ fill: "rgba(0,0,0,.25)" }}
                    />
                  ) : (
                    <Icon
                      type="close-circle"
                      className="ant-calendar-picker-icon"
                      style={{ fill: "rgba(0,0,0,.25)", cursor: "pointer" }}
                      onClick={e => this.handleClose(e)}
                    />
                  )}
                </span>
              </div>
            ) : (
              <Fragment>
                <div className={styles.monthRangeBox}>
                  <div className={styles.monthHeader}>
                    <span
                      className="ant-calendar-range-picker-input"
                      style={{ display: "inline-block" }}
                      role={
                        value[0]
                          ? moment(value[0]).format("YYYY-MM-DD")
                          : "开始日期"
                      }
                    >
                      {value[0]
                        ? moment(value[0]).format("YYYY-MM-DD")
                        : "开始日期"}
                    </span>
                    <span>~</span>
                    <span
                      className="ant-calendar-range-picker-input"
                      style={{ display: "inline-block" }}
                      role={
                        value[0]
                          ? moment(value[1]).format("YYYY-MM-DD")
                          : "结束日期"
                      }
                    >
                      {value[0]
                        ? moment(value[1]).format("YYYY-MM-DD")
                        : "结束日期"}
                    </span>
                  </div>
                </div>
                <MonthPicker
                  value={value[0]}
                  open={true}
                  dropdownClassName={styles.left}
                  getCalendarContainer={() => document.getElementById("parent")}
                  disabledDate={this.handleDisabledMonth}
                  onChange={this.handleMonthChange}
                  className={styles.startMonth}
                />
                <MonthPicker
                  value={value[1]}
                  open={true}
                  dropdownClassName={styles.right}
                  getCalendarContainer={() => document.getElementById("parent")}
                  disabledDate={this.handleDisabledMonth}
                  onChange={this.handleMonthChange}
                />
              </Fragment>
            )}
          </div>
        )}
      </div>
    );
  }
}
